package service;

import user.Student;

public class StuService {
    private Student[] students = new Student[1];//保存学生对象

    public StuService() {
        students[0] = new Student("mary", '女', 20, "12345678", "0123456",
                "18200290858", "1班", 100);
    }

    //add方法，返回boolean
    public boolean add(Student newStudent) {
        //先判断学生是否已经注册过了
        for (int i = 0; i < students.length; i++) {
            if(students[i].equals(newStudent)){
                return false;
            }
        }

        Student[] newArr = new Student[students.length + 1];//定义一个新数组，比原数组大一
        for (int i = 0; i < students.length; i++) {//遍历数组赋值
            newArr[i] = students[i];
        }

        newArr[students.length] = newStudent;//把新对象的添加到最后
        students = newArr;//重新赋值
        return true;
    }

    //del方法，返回boolean
    public boolean del(int delNum) {
        //遍历查找要删除的学生信息对应的下标，编号-1为下标
        int indext = -1;
        for (int i = 0; i < students.length; i++) {
            if (delNum == students[i].getNum()) {//要删除房屋对应的编号，是数组下标为i的元素
                indext = i;//记录下要删除的下标
            }
        }
        if (indext == -1) {
            return false;
        } else {
            //如果找到，就删除
            //1.创建一个新数组，大小为students.length-1，按顺序赋值，当下标为i时就跳过
            Student[] newStu = new Student[students.length - 1];
            for (int i = 0; i < students.length - 1; i++) {
                if (i >= indext) {
                    newStu[i] = students[i + 1];
                } else {
                    newStu[i] = students[i];
                }
                newStu[i].setNum(i + 1);//序号
            }
            students = newStu;
            Student.totalStu --;
            return true;
        }
    }

    //查找某个学生
    public Student FindStu(int searchNum) {
        for (int i = 0; i < students.length; i++) {
            if (searchNum == students[i].getNum()) {//找到编号
                return students[i];
            }
        }
        return null;
    }

    //list方法，返回students信息
    public Student[] list() {
        return students;
    }
}
